﻿/********************************************************************************
** 作者： Mick
** 邮箱： zheng_jinfan@126.com
** 主页： http://www.zhengjinfan.cn
** 创始时间：2016-2-17
** 描述：
**      [辅助类]分词组件辅助类
*********************************************************************************/
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace BestEasyCMS.Framework.Util
{
    /// <summary>
    /// [辅助类]分词组件辅助类
    /// </summary>
    public class ParticipleUtil
    {
        #region 构造实例

        /// <summary>
        /// 分词组件辅助类
        /// </summary>
        private ParticipleUtil()
        {
        }

        #endregion

        /// <summary>
        /// 获取分词字典
        /// </summary>
        /// <param name="keyword">需要分词的内容</param>
        /// <param name="maxLength">执行单词（空格为单词的分隔符）分词的最大长度,内容超过此长度将不进行拆分</param>
        /// <returns>分词字典</returns>
        public static Dictionary<string, int> GetParticipleDictionary(string keyword, int maxLength)
        {
            var list = new Dictionary<string, int>();
            foreach (string kw in keyword.Split(' '))
            {
                list.Add(kw, kw.Length);

                if (!Regex.IsMatch(kw, "[a-zA-Z0-9]+"))
                {
                    if (kw.Length > 1 && kw.Length <= maxLength)
                    {
                        for (int i = 2; i < kw.Length; i++)
                        {
                            string temp = kw.Substring(0, i);
                            if (!list.ContainsKey(temp))
                                list.Add(temp, temp.Length);
                        }
                    }

                    if (kw.Length > 1 && kw.Length <= maxLength)
                    {
                        for (int i = kw.Length - 2; i >= 1; i--)
                        {
                            string temp = kw.Substring(i);
                            if (!list.ContainsKey(temp))
                                list.Add(temp, temp.Length);
                        }
                    }
                }
            }
            return list;
        }
    }
}